use super::{
    ChainSpec, ContributionAndProof, Domain, EthSpec, Fork, ForkName, Hash256, SecretKey,
    Signature, SignedRoot, SyncCommitteeContribution, SyncSelectionProof,
};
use crate::context_deserialize;
use crate::test_utils::TestRandom;
use serde::{Deserialize, Serialize};
use ssz_derive::{Decode, Encode};
use test_random_derive::TestRandom;
use tree_hash_derive::TreeHash;

/// A Validators signed contribution proof to publish on the `sync_committee_contribution_and_proof`
/// gossipsub topic.
#[derive(
    Debug,
    Clone,
    PartialEq,
    Serialize,
    Deserialize,
    Encode,
    Decode,
    TestRandom,
    TreeHash,
    arbitrary::Arbitrary,
)]
#[serde(bound = "E: EthSpec")]
#[arbitrary(bound = "E: EthSpec")]
#[context_deserialize(ForkName)]
pub struct SignedContributionAndProof<E: EthSpec> {
    /// The `ContributionAndProof` that was signed.
    pub message: ContributionAndProof<E>,
    /// The validator's signature of `message`.
    pub signature: Signature,
}

impl<E: EthSpec> SignedContributionAndProof<E> {
    /// Produces a new `SignedContributionAndProof` with a `selection_proof` generated by signing
    /// `aggregate.data.slot` with `secret_key`.
    ///
    /// If `selection_proof.is_none()` it will be computed locally.
    pub fn from_aggregate(
        aggregator_index: u64,
        contribution: SyncCommitteeContribution<E>,
        selection_proof: Option<SyncSelectionProof>,
        secret_key: &SecretKey,
        fork: &Fork,
        genesis_validators_root: Hash256,
        spec: &ChainSpec,
    ) -> Self {
        let message = ContributionAndProof::from_aggregate(
            aggregator_index,
            contribution,
            selection_proof,
            secret_key,
            fork,
            genesis_validators_root,
            spec,
        );

        let epoch = message.contribution.slot.epoch(E::slots_per_epoch());
        let domain = spec.get_domain(
            epoch,
            Domain::ContributionAndProof,
            fork,
            genesis_validators_root,
        );
        let signing_message = message.signing_root(domain);

        SignedContributionAndProof {
            message,
            signature: secret_key.sign(signing_message),
        }
    }
}
